var chat=function(){
    var connectState = false;		//连接状态
    var needReconnect = false;	//是否需要进行重连
    var reconnect2Send = false;	//重连成功后是否发送输入框内容，按发送之后，会将此值设置为true，发送完内容设置为false
    var socket = null;
    var sender = 0;
    var receiver = 0;
    var userCode="";
    this.init=function(s,r){
        sender=s;
        receiver=r;
    };
    //断开连接
	this.disconnect = function () {
        if (connectState) {
            socket.send("[disconnect]102");
            console.log("disconnect by user");
        	needReconnect = true;
        }
    };
    this.connect=function (host) {
        if ('WebSocket' in window) {
            socket = new WebSocket(host);
        } else if ('MozWebSocket' in window) {
            socket = new MozWebSocket(host);
        } else {
            console.log('Error: WebSocket is not supported by this browser.');
            return;
        }
		//连接发生错误的回调方法
		socket.onerror = function(event) {
			console.log("onerror"+event);
			alert("连接失败");
		};
        //连接成功建立的回调方法
        socket.onopen = function () {
            connectState = true;
            console.log('Info: WebSocket connection opened.');
            if (reconnect2Send) {
                sendMessage();
                reconnect2Send = false;
            }
        };
        //连接关闭时回调方法
        socket.onclose = function () {
            connectState = false;
            console.log('Info: WebSocket closed.');
            if (needReconnect) {
                return;
            }
            setTimeout(function () {//断线1秒后，自动检测重连
                if (!connectState) {
                    connecting(true);
                }
            }, 1000);
        };
        //接收到消息的回调方法
        socket.onmessage = function (message) {
            console.log("onmessage:"+message.data);
        };
    };
	this.connecting=function (reConnect) {
		userCode="fcBCP7";
		//host = window.location.host;
		var host = "localhost:8080/websockets";
	    var url = host + '/chat.ws?s=' + sender + "&r=" + receiver + "&co=" + userCode+ "&source=1";
	    if (reConnect) {
	        url = url + "&rc=1";
	    }
	    if(host.indexOf(".net")>-1){	//线上使用wss（加密）
	    	this.connect('wss://' + url);
	    }else{	//开发使用普通的ws
	    	this.connect('ws://' + url);
	    }
	};
    this.sendMessage=function () {
        if(needReconnect){
        	return;
        }
        var message=$("#msg").val();
        if (message != '') {
            if (!connectState) {	//断线重连
                reconnect2Send = true;
                connecting(true);
            } else {
                socket.send(message);
            }
        }
    }
};
var chatObj=null;
function init(){
    chatObj=new chat();
    chatObj.init(76,227);
    chatObj.connecting(false);
}
function start(){
    chatObj.sendMessage();
}